<template>
    <div>
        <!--添加按钮和模态框-->
        <a-button type="primary" @click="showModal('add')">
            添加
        </a-button>
        <!--编辑对话框-->
        <a-modal
                :visible="visible"
                :title= "modelTitle"
                :confirm-loading="confirmLoading"
                okText='确认'
                cancel-text="取消"
                @cancel="hideModel"
                @ok="submit"
        >
            <!--表单-->
            <a-form-model :model="form">
                <a-form-model-item label="名称">
                    <a-input v-model="form.title" />
                </a-form-model-item>
                <a-form-model-item label="状态">
                    <a-radio-group v-model="form.status">
                        <a-radio value="1">
                            启用
                        </a-radio>
                        <a-radio value="0">
                            禁用
                        </a-radio>
                    </a-radio-group>
                </a-form-model-item>
            </a-form-model>
        </a-modal>

        <!--授权对话框-->
        <a-modal
                :visible="authorize_visible"
                title= "角色授权"
                :confirm-loading="authorize_confirmLoading"
                okText='确认'
                cancel-text="取消"
                @cancel="hideAuthorizeModel"
                @ok="submitAuthorize(nowEditRoleId)"
        >
            <!--&lt;!&ndash;授权树选择&ndash;&gt;
            <a-tree
                    v-model="authorize_value"
                    style="width: 100%"
                    :tree-data="treeData"
                    tree-checkable
                    showCheckedStrategy="SHOW_PARENT"
                    :filterTreeNode="searchFilterTreeNode"
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    placeholder="请选择权限"
                    @expand="onExpand"
                    @check="onBusinessSelectChange"
            />-->
            <a-tree
                    v-model="authorize_value"
                    checkable
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :selected-keys="selectedKeys"
                    :tree-data="treeData"
                    :showLine="true"
                    @expand="onExpand"
                    @check="onBusinessSelectChange"
            />
        </a-modal>

        <!--表格-->
        <!--
            :columns="columns"  表头数据
            :data-source="data" 表格数据
            rowKey="id"   id为 data 中的一个属性
            :loading="loading" 表格是否load
            :pagination="pagination" 分页参数
        -->
        <a-table :columns="columns" :data-source="data" rowKey="id" :loading="loading" :pagination="pagination"  >
            <span slot="status" slot-scope="text, record, index" v-if="record.id !== 1">
                <div v-if="text == 1">
                    <a-button type="primary" @click="changeActive(text, record, index)">已启用</a-button>
                </div>
                <div v-else>
                    <a-button type="danger" @click="changeActive(text, record, index)">已禁用</a-button>
                </div>
            </span>
            <!--插槽一定要在表格组件标签中-->
            <!--定义插槽渲染-->
            <!--
                slot="action" 表示是在columns（某列）中的表头值为action中插入标签，往这个位置插入插槽span中间的内容
                slot-scope="text, record, index"
                    text    表示当前行当前列的值
                    record  表示当前行的数据
                    index   表格索引
            -->
            <span slot="action" slot-scope="text, record, index">
                 <div v-if="record.id === 1">
                    <span>超级管理员不能编辑</span>
                </div>
                <div v-else>
                    <a-button type="primary" @click="edit(text, record, index)">编辑</a-button>
                    <a-button type="primary" @click="authorizeEdit(text, record, index)">授权</a-button>
                    <!--气泡确认框-->
                    <a-popconfirm
                            title="是否删除?"
                            @confirm="() => del(text, record, index)"
                    >
                        <a-button type="danger">
                            删除
                        </a-button>
                    </a-popconfirm>
                </div>

            </span>

            <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                        v-if="dataSource.length"
                        title="Sure to delete?"
                        @confirm="() => onDelete(record.key)"
                >
                    <a href="javascript:;">Delete</a>
                </a-popconfirm>
            </template>
        </a-table>

    </div>
</template>

<script>
    export default {
        // 在实例中使用 components 属性注册需要用到的组件
        //注册组件
        data() {
            return {
                //表格数据
                data : [],
                /**
                 * 表头数据
                 * title 为表头的标题
                 * dataIndex为列数据在数据项中对应的 key
                 * scopedSlots 对应插槽
                 */
                columns : [
                    {
                        title: '名称',
                        dataIndex: 'title',
                    },
                    {
                        title: '状态',
                        dataIndex: 'status',
                        scopedSlots: {customRender: 'status'},
                    },
                    {
                        title: '操作',
                        dataIndex: 'action',
                        //使用插槽
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                //表格load标志
                loading : true,
                //表格分页参数
                pagination: {
                    //pageNo: 2,
                    current: 1,
                    pageSize: 10, // 默认每页显示数量
                    showSizeChanger: true, // 显示可改变每页数量
                    pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
                    showTotal: total => `共 ${total} 条数据`, // 显示总数
                    onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize), // 改变每页数量时更新显示
                    onChange:(current,pageSize)=>this.changePage(current,pageSize),//点击页码事件
                    total:0 //总条数
                },
                //模态对话框标题
                modelTitle: '',
                //编辑模态框是否显示
                visible: false,
                //授权模态框是否显示
                authorize_visible: false,
                //表单load
                confirmLoading: false,
                //授权确认load
                authorize_confirmLoading: false,

                //tree select 树选择
                treeData: [],

                //tree select 树选择最深子节点
                test:[],
                //授权选择的
                authorize_value : [],
                //树控件默认选中
                selectedKeys:[],
                //树控件所有勾选包含半勾选父节点
                allSelectedNodes : [],
                //树控件展开
                expandedKeys: [],
                //是否自动展开父节点
                autoExpandParent: true,

                //from 初始化
                form : {
                    id : 0,
                    title : '',
                    status : '1',

                    //操作类型
                    operation_type : 'add',
                }
            };
        },
        //页面渲染之前,$el创建之后 去加载
        mounted() {
            //获取列表
            this.getList();

            //获取授权菜单
            this.getAuthorizeMenu();
        },
        methods: {
            /**
             * 树选择框,构造转换，转换后端数据为树形选择需要的数据
             * @param data  后端数据
             * @returns {[]}  返回结构
             */
            convertToTreedata(data){
                //console.log(data, '数据构造........')
                var returnData = [];
                //遍历数据
                for(var i = 0; i < data.length; i++){
                    var tempObj = {
                        title : data[i].title,
                        value : data[i].id,
                        key : data[i].id
                    };

                    //判断是否存在子节点，如果存在则递归
                    if('child_node' in data[i]){
                        tempObj.children = this.convertToTreedata(data[i].child_node);
                    }
                    //push到数据数组中
                    returnData.push(tempObj);
                }
                return returnData;
            },
            //获取授权菜单
            getAuthorizeMenu(){
                this.loading = true;
                this.axios.get(process.env.VUE_APP_API_URL + this.urls.getMenus).then((data) => {
                    //修改loading 状态
                    this.loading = false;
                    //数据
                    //this.data = data.data.data;
                    //树选择,下拉框重新构造
                    //转换树菜单选择
                    var res = this.convertToTreedata(data.data.data);
                    //脱掉一层再进行push
                    this.treeData.push(...res);
                    // console.log(this.treeData)
                });
            },

            onExpand(expandedKeys) {
                // console.log('onExpand', expandedKeys);
                //如果没有设置autoExpandParent为false，如果子对象展开，则父对象不能折叠。
                //或者，你可以删除所有展开的子键。
                this.expandedKeys = expandedKeys;
                this.autoExpandParent = false;
            },
            onBusinessSelectChange(selectedKeys, info) {
                /*console.log('selectedKeys changed: ', selectedKeys);
                console.log('info changed: ', info);*/

                // 已勾选子节点以及半勾选状态的父节点
                this.allSelectedNodes = selectedKeys.concat(info.halfCheckedKeys);
                this.businessSelectedRowKeys = selectedKeys;
                /*console.log('所有节点包含半勾选父节点', this.allSelectedNodes);
                console.log('所有节点不包含半勾选父节点', this.businessSelectedRowKeys);*/

            },

            //多选搜索过滤
           /* searchFilterTreeNode(inputValue, treeNode){
                /!*console.log(inputValue);
                console.log(treeNode);
                //组件数据
                console.log(treeNode.componentOptions.propsData.title);
                //原数据
                console.log(treeNode.data.props.title);*!/
                return (
                    treeNode.componentOptions.propsData.title.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0
                );
            },*/


            //获取列表
            getList(param) {
                //初始化分页参数
                if(param === undefined || param === null){
                    param = {
                        current : 1,
                        pageSize : 10
                    }
                }
                this.loading = true;
                this.axios.get(process.env.VUE_APP_API_URL + this.urls.role_list,{params: {
                        pageNow : param.current,
                        pageSize : param.pageSize,
                    }}).then((data) => {
                    //修改loading 状态
                    this.loading = false;
                    //数据
                    this.data = data.data.data.data;
                    //分页参数
                    //更新数据总条数
                    this.pagination.total = data.data.data.lineCount;
                });
            },
            //点击页码事件
            changePage(current,pageSize) {
                /*console.log(page, '当前页.......');
                console.log(pageSize, '每页大小.......');*/
                this.pagination.current = current;
                this.pagination.pageSize = pageSize;
                this.getList({
                    current : current,
                    pageSize : pageSize
                })
            },

            //每页显示数量改变的事件
            changePageSize(current, pageSize){
                /*console.log(current, '当前页.......');
                console.log(pageSize, '每页大小.......');*/
                this.pagination.current = current;
                this.pagination.pageSize = pageSize;
                this.getList({
                    current : current,
                    pageSize : pageSize
                })
            },
            //显示模态对话框
            showModal(type) {
                //console.log(type, 'type........');
                //设置对话框标题
                type === 'add'? this.modelTitle = '添加':this.modelTitle = '编辑'
                this.visible = true;
            },
            //关闭模态框
            hideModel() {
                this.visible = false;
                this.resetForm();
            },

            //关闭授权模态框
            hideAuthorizeModel() {
                this.authorize_visible = false;
                //重置授权树选择
                this.authorize_value = [];
                //重置展开状态
                this.expandedKeys = [];
            },
            //重置form状态
            resetForm(){
                this.form =  {
                    id : 0,
                    title : '',
                    status : '1',

                    //操作类型
                    operation_type : 'add',
                }
            },

            //确认提交
            submit(){
                //基准地址
                var url = process.env.VUE_APP_API_URL;
                //接口路由
                if(this.form.operation_type === 'add'){
                    this.pagination.current = 1;
                    url += this.urls.role_add;
                }
                if(this.form.operation_type === 'edit'){
                    url += this.urls.role_edit;
                }
                if(this.form.operation_type === 'del'){
                    url += this.urls.role_del;
                }
                if(this.form.operation_type === 'change_status'){
                    url += this.urls.role_change_status;
                }
                //发送请求
                this.axios.post(url, this.form).then((data) => {

                    //错误提示
                    /*if(data.data.code !== 200){
                        this.$message.error(data.data.msg);
                        return;
                    }*/

                    //重新刷新表格
                    this.data = this.getList()
                    //恢复默认
                    this.resetForm();
                    //关闭按钮的load状态
                    this.confirmLoading = false;
                    //关闭模态框
                    this.visible = false;

                    //改变页码
                    if(this.form.operation_type === 'add'){
                        this.pagination.current = 1;
                    }
                });
            },

            //授权提交
            submitAuthorize(role_id){
                //发送请求
                this.axios.post(process.env.VUE_APP_API_URL + this.urls.role_authorize, {
                    'role_id':role_id,
                    'node_ids':this.allSelectedNodes
                }).then((data) => {
                    //console.log(data)
                    //错误提示
                    /*if(data.data.code !== 200){
                        this.$message.error(data.data.msg);
                        return;
                    }*/
                    //关闭
                    this.hideAuthorizeModel();

                });
            },

            //编辑
            edit(text, record, index) {
                //设置模态框的form表单的值和选中
                this.form.id = record.id;
                this.form.title = record.title;
                this.form.status = ''+record.status;



                //切换用户名input 状态,改为禁用
                this.form.username_disable = true;
                //切换操作类型
                this.form.operation_type = 'edit';

                //显示模态框
                this.showModal();
            },

            //删除
            del(text, record, index) {
                //console.log('删除.........');
                this.form.id = record.id;
                //切换操作类型
                this.form.operation_type = 'del';
                //提交
                this.submit();
            },

            // 1.循环遍历出最深层子节点，存放在一个数组中
            getTreeChildren(data){
                data&&data.map(item=>{
                    if(item.children && item.children.length > 0){
                        this.getTreeChildren(item.children);
                    }else{
                        this.test.push(item.key);
                    };
                    return null;
                });
                return this.test;
            },
            // 2.将后台返回的含有父节点的数组和第一步骤遍历的数组做比较
            // 3.如果有相同值，将相同值取出来，push到一个新数组中
            compareItem(all_data,child_data){
                let uniqueChild = [];
                for(var i in child_data){
                    for(var k in all_data){
                        if(all_data[k] === child_data[i]){
                            uniqueChild.push(all_data[k]);
                        }
                    }
                }
                return uniqueChild;
            },

            //授权编辑
            authorizeEdit(text, record, index) {
                //显示对话框
                this.authorize_visible = true;
                //重置授权树选择
                this.authorize_value = []

                this.nowEditRoleId = record.id

                this.axios.get(process.env.VUE_APP_API_URL + this.urls.getNodesByRoleId,{params: {
                        id : record.id,
                    }}).then((data) => {
                        console.log(data.data.data, 'node。。。。。。。');

                        //遍历后台数据
                        var all_data = [];
                        for(var i = 0; i < data.data.data.length; i++){
                            all_data.push(data.data.data[i].id);
                        }
                        //1.获取组件最深子节点,tree的data
                        var child_data = this.getTreeChildren(this.treeData);
                        console.log(child_data,'child_data........');
                        //2,3 获取相同的子节点
                        console.log(all_data,'all_data........');
                        var uniqueChild = this.compareItem(all_data,child_data);
                        console.log(uniqueChild,'uniqueChild........');
                        //4.利用这个新的重组的数组给Tree组件selected赋值
                        this.authorize_value = uniqueChild;

                });
            },
            //改变状态
            changeActive(text, record, index) {
                //console.log(record)
                this.form.id = record.id;
                //切换操作类型
                this.form.operation_type = 'change_status';
                //提交
                this.submit();
            },

        },
    };
</script>

<style scoped>

</style>